using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Text;

namespace Multiplicity.Reflection.Tests {
    static class TestAssemblyWriter {

        public static byte[] CompileAssembly(string csharpCode) {
            using (CodeDomProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider()) {

                byte[] image = null;

                CompilerParameters cp = new CompilerParameters();
                CompilerResults r = codeProvider.CompileAssemblyFromSource(cp, csharpCode);

                if (r.Errors.Count == 0) {
                    image = File.ReadAllBytes(r.PathToAssembly);
                    File.Delete(r.PathToAssembly);

                    return image;
                }

                throw new Exception("errors!\n" + OutputErrors(r.Errors).ToString());
            }
            
        }
        
        static StringBuilder OutputErrors(CompilerErrorCollection errors) {
            StringBuilder ret = new StringBuilder();

            foreach (CompilerError err in errors) {
                string severity = err.IsWarning ? "warning" : "error";
                ret.AppendFormat("({0},{1}): {4} CS{2}: {3}\n", err.Line, err.Column, err.ErrorNumber, err.ErrorText, severity);
            }

            return ret;
        }

    }
}
